package com.platform.common.handler;

import com.platform.common.annotations.ResponseResult;
import com.platform.common.bean.BaseException;
import com.platform.common.bean.Result;
import com.platform.common.util.CommonConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * describe:API统一返回样式的处理器
 *
 * @author Administrator
 * @date 2019/12/15
 * @Time 11:32
 */
@Slf4j
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    /**
     * 判断是否是ResponseResult注解
     * @param methodParameter 方法参数
     * @param aClass 类
     * @return 返回是否是ResponseResult注解
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (servletRequestAttributes == null){
            return false;
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        ResponseResult responseResult = (ResponseResult)request.getAttribute(CommonConst.RESPONSE_RESULT_ANN);
        return responseResult != null;
    }

    /**
     * 返回数据前进行封装
     * @param body 返回客户端的数据
     * @param methodParameter methodParameter
     * @param mediaType mediaType
     * @param aClass aClass
     * @param serverHttpRequest serverHttpRequest
     * @param serverHttpResponse serverHttpResponse
     * @return REST风格统一返回的Bean对象
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof Result){
            //如果在其他类已进行了REST对象封装，则不需要再次封装
            return body;
        }
        //判断是否是Optional对象
        if (body instanceof Optional){
            //判断是否是空对象，如果是返回查询错误
            return ((Optional) body).map(Result::success).orElse(Result.failure());
        }
        if(body instanceof BaseException){
            return Result.failure(((BaseException)body).getCode(), ((BaseException)body).getMessage());
        }
        return Result.success(body);
    }
}
